package com.TheyChat.service.config.auth;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.TheyChat.service.config.auth.entity.UserAuthInfo;
import com.TheyChat.service.config.core.enums.UserTypeEnum;

import java.util.Calendar;
import java.util.Date;


/***
 * 验证类
 */
public class AuthUtils {

    private static final String TOKEN_SECRET = "6ae6acab8f6711eeb9d6d49390175afb";

    /**
     * 签发对象：这个用户的id
     * 签发时间：现在
     * 有效时间：30天
     * 载荷内容：暂时设计为：用户名，用户组织id
     * 加密密钥：这个人的id加上一串字符串
     */
    public static String createToken(UserAuthInfo authInfo) {

        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE, 60 * 24 * 30);
        Date expiresDate = nowTime.getTime();

        return JWT.create()  //签发对象
                .withIssuedAt(new Date())    //发行时间
                .withExpiresAt(expiresDate)  //有效时间
                .withClaim("id", authInfo.getId())
                .withClaim("username", authInfo.getUsername())
//                .withClaim("userRealName", authInfo.getUserRealName())
                .withClaim("orgId", authInfo.getOrgId())
//                .withClaim("projOrgId", authInfo.getProjOrgId())
//                .withClaim("projOrgCode", authInfo.getProjOrgCode())
                //组织机构：
//                .withClaim("orgName", authInfo.getOrgName())
//                .withClaim("projOrgName", authInfo.getProjOrgName())
//                .withClaim("userProjectOrgLevelCode", authInfo.getUserProjectOrgLevelCode())
//                .withClaim("userProjectOrgLevel", authInfo.getUserProjectOrgLevel())
//                .withClaim("projOrgType", authInfo.getProjOrgType())
                // 用户类型：开投or供方
                .withClaim("userType", authInfo.getUserType().getValue())
                .sign(Algorithm.HMAC256(TOKEN_SECRET));   //加密
    }


    /****
     * 根据token获取当前登录用户信息（如果未登录或者是无效的token则返回NULL
     * @param token
     * @return
     */
    public static UserAuthInfo hasAuth(String token) {
        if (token == null) {
            return null;
        }
        try {
            JWTVerifier build = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();
            DecodedJWT verify = build.verify(token);
            if (verify != null && verify.getToken() != null && verify.getToken().length() > 0) {
                UserAuthInfo authInfo = new UserAuthInfo();
                /**
                * 这里一定要用asString,因为toString出来的结果自带两个双引号“”,会让数据不正常*/
                authInfo.setId(verify.getClaim("id").asString());
                authInfo.setUsername(verify.getClaim("username").asString());
//                authInfo.setUserRealName(claims.get("userRealName").asString());
                authInfo.setOrgId(verify.getClaim("orgId").asString());
                authInfo.setRoleId(verify.getClaim("roleId").asString());
//                authInfo.setProjOrgId(claims.get("projOrgId").asString());
//                authInfo.setProjOrgCode(claims.get("projOrgCode").asString());
                //组织名称：
//                authInfo.setOrgName(claims.get("orgName").asString());
//                authInfo.setProjOrgName(claims.get("projOrgName").asString());
                // authInfo.setProjOrgCode(claims.get("projOrgCode").asString());
//            authInfo.setUserProjectOrgLevel(claims.get("userProjectOrgLevel").asInt());
//                authInfo.setProjOrgType(claims.get("projOrgType").asString());
                authInfo.setUserType(UserTypeEnum.create(verify.getClaim("userType").asInt()));
                authInfo.setOrgCode(verify.getClaim("orgCode").asString());
//                authInfo.setLevelCode(verify.getClaim("levelCode").asString());
                return authInfo;
            }
            return null;
        } catch (IllegalArgumentException e) {
            return null;
        } catch (JWTVerificationException e) {
            return null;
        }

    }
    public static int getUserType(String token){
        try{
            DecodedJWT jwt=JWT.decode(token);
            int userType=  jwt.getClaim("userType").asInt();
            return userType;
        }catch (JWTDecodeException e)
        {
            return 0;
        }
    }
}
